// 生成jwt
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from '../../utils/constants';
import { UserService } from 'src/service/user/user.service';
import { BUSINESS_ERROR_CODE } from 'src/config/error.code';
export interface JwtPayload {
  name: string;
  id: string | number;
  phone: string;
}
@Injectable()
// 验证请求头中的token
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
      // secretOrKey: configService.get('JWT_SECRET') ?? 'secret',
      passReqToCallback: true, // 注意点 ②
    });
  }
  // JWT验证 - Step 4: 被守卫调用
  async validate(req, payload: JwtPayload) {
    let exitUser = await this.userService.getUser(payload);
    if (!exitUser) {
      // TOKEN_EXPIRED
      return {
        code: BUSINESS_ERROR_CODE.TOKEN_EXPIRED,
        result: 'token已失效',
      };
    }
    return {
      ...payload,
    };
  }
}
